import React, {useEffect, useState} from 'react'
import { Form, Button, Input, Modal, Row, Col,Card,Upload,Select,DatePicker,message,InputNumber} from 'antd'
import { connect } from 'umi'
import EditAwardTable from './EditAwardTable'
import moment from 'moment';
import { getAwardApplicantById } from '../../service'
import {getUploadUrl} from '@/utils/upload'
import {UploadOutlined} from '@ant-design/icons';

const FormItem = Form.Item;
const { TextArea } = Input;
const formLayout = {
  labelCol: { span: 7 },
};
const { Option } = Select;

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];

const CreateForm = (props) => {

  const { onSubmit, onCancel,visible,currentUser,global = {},reanpu,loading,record } = props;
  const {options = {}} = global;
  const {orgTree = []} = options;
  const [form] = Form.useForm();
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);
  const [orgList,setOrgList] = useState([]);
  const [list,setList] = useState([]);
  const [count,setCount] = useState(0);
  const [sum,setSum] = useState(0);
  const [delList,setDelList] = useState([]);

  useEffect(() => {
    if(visible && record){
      getAwardApplicantById(record.id).then(res => {
        let temp = [];
        res.map((item) => {
          temp.push(parseInt(item.orgId));
        });
        setList(res);
        form.setFieldsValue({...record,applyTime:moment(record.applyTime),type:record.type,
          urlIds:record.fileUrl,awardOrgName:temp
        });
        setCount(record.totalAmount);
        onSum(res);
      });
      let fileUrlList = record.fileUrl?.length > 0 ? record.fileUrl.split(',') : [];
      setFileUploadUrls(fileUrlList);
      if(fileUrlList.length > 0){
        fileUrlList.forEach((item,index) =>{
          uploadedFiles.push({
            uid: index,
            name: item.split('----')[1],
            status: 'done',
            url: item,
          })
        });
      }
    }else if(currentUser){
      form.setFieldsValue({applicantName:currentUser.name,orgName:currentUser.orgname,applyTime:moment(),...currentUser});
    }
  }, [visible]);

  const fileList = {
    name: 'file',
    multiple: false,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls, res.file.response]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  const onFormCancel = () => {
    form.resetFields();
    setOrgList([]);
    onCancel();
    uploadedFiles = [];
    setFileUploadUrls([]);
    setSum(0);
    setCount(0);
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    let temp = fieldsValue.awardApplicantEntityArrayList?.length > 0 ? fieldsValue.awardApplicantEntityArrayList : list;
    if(temp.length > 0){
      temp.forEach(item => {
        if(item.awardType === null){
          message.error("奖罚类型不能为空！");
          return;
        }else if(item.amount === null || item.amount === 0){
          message.error("分配金额不能为空！");
          return;
        }
      })
    }else{
      message.error("奖罚包列表不能为空！");
      return;
    }
    if(sum > count){
      message.error("奖罚总数不能超过总金额！");
      return;
    }
    form.resetFields();
    setOrgList([]);
    onSubmit({...fieldsValue,fileUrlList:fileUploadUrls,id:record && record.id,awardApplicantEntityArrayList:temp});
    uploadedFiles = [];
    setFileUploadUrls([]);
    setSum(0);
    setCount(0);
  };

  const onChangeOrgId = (e,value) =>{
    setOrgList(value);
  };

  const OnSetCount = (value) =>{
    setCount(value);
  };

  const onSum = (value) => {
    let tempSum = 0;
    value.map((item) => {
      let temp = parseInt(tempSum);
      tempSum =  parseInt(item.distributionAmount) + temp;
    });
    setSum(tempSum);
  };

  const delSelect = (value) => {
    setDelList(value);
  };

  const distribution = () => (<><div>（ 金额分配 ： {sum}/{count} ）</div></>);

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="applicantName" label="申请人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="department" label="申请部门">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyTime" label="申请日期">
              <DatePicker disabled={true} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="orgName" label="申请公司">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="type" label="奖罚种类" rules={[{required: true, message: '奖罚种类不能为空！'}]}>
              <Select placeholder="请选择奖罚种类" showSearch filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }>
                {reanpu && reanpu.map((item, index) => {
                  return (
                    <Option value={`${item.code}`} key={index}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem label={<><span className='asterisk'>*</span>总金额</>}>
              <FormItem noStyle name="totalAmount" rules={[{required: true, message: '总金额不能为空！'},({
                validator(rule,value) {
                  let pattern = /(^[1-9]([0-9]*)$|^[0-9]$)/;
                  if (pattern.test(value)) {
                    return Promise.resolve();
                  }
                  return Promise.reject('请输入数字类型的正确金额');
                },
              })]}>
                <InputNumber style={{width:'90%',marginRight:'10px'}} onChange={(value) => OnSetCount(value)}/>
              </FormItem>
              元
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="awardName" label="奖罚名称" rules={[{required: true,message: '奖罚名称不能为空！'}]}>
              <Input/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="awardOrgName" label="奖罚公司" rules={[{required: true,message: '奖罚公司不能为空！'}]}>
              <Select placeholder="请选择奖罚公司" mode="multiple" allowClear onChange={(e,value) => onChangeOrgId(e, value)} onDeselect={delSelect}>
                {orgTree && orgTree.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.title}
                    </Option>
                  )
                })}
              </Select>
              {/*<Input/>*/}
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="urlIds" label="上传附件" rules={[{required: true,message: '奖罚附件不能为空！'}]}>
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Card title="奖罚公司分配" bordered={false} extra={distribution()} className='widthStyle' style={{marginBottom: 24}}>
            <FormItem name="awardApplicantEntityArrayList">
              <EditAwardTable onChange={onSum} orgList={orgList} list={list} delOrgId={delList}/>
            </FormItem>
          </Card>
          <Col span={24}>
            <FormItem name="remark" labelCol={{span: 2}} label="奖罚说明" rules={[{required: true,message: '请输入奖罚说明！'}]}>
              <TextArea rows={8} className='widthStyle'/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" loading={loading} onClick={() => handleSubmit()}>确认</Button>
      </>
    )
  };

  return (
    <Modal
      width={'70%'}
      destroyOnClose
      title="奖罚包分配"
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
};


export default connect(({ user, personnel,global }) => ({
  personnel,
  currentUser: user.currentUser,
  global
}))(CreateForm)
